package net.dntuan.training.mvc.dao.impl;

import java.io.Serializable;
import java.util.List;

import net.dntuan.training.mvc.dao.BaseDao;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

// TODO why is this class marked as abstract class?
public abstract class BaseDaoImpl<T extends Serializable> implements BaseDao<T> {

    protected Class<T> clazz;

    @Autowired
    SessionFactory sessionFactory;

    public void setClazz(final Class<T> clazz) {
        this.clazz = clazz;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T findOne(final Long id) {
        return (T) getCurrentSession().get(clazz, id);
    }

    @Override
    public void save(T entity) {
        getCurrentSession().persist(entity);
    }

    @Override
    public void update(T entity) {
        getCurrentSession().update(entity);
    };

    @Override
    public void delete(T entity) {
        getCurrentSession().delete(entity);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> findAll() {
        Criteria criteria = getCurrentSession().createCriteria(clazz);
        return criteria.list();
    }

    protected final Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }
}
